﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using mjc.sync.files.rules;

namespace mjc.sync.files.rules
{
    public class EmptyDirectoryFilter : DirectoryDataFilter
    {
        private bool _useRecursiveCheck = false;

        public bool Recursive {
            get { return _useRecursiveCheck; }
            set { this._useRecursiveCheck = value; }
        }

        // I'd like add some extension methods that perform #isNull()...
        public override bool Matches(String path)
        {
            if (path == null || String.Empty.Equals(path.Trim()) )
            {
                return false;
            }

            DirectoryInfo directoryInfo = new DirectoryInfo(path);
            if (directoryInfo.Exists)
            {
                return Matches(directoryInfo);
            }
            return false;
        }

        public override bool Matches(DirectoryInfo directoryInfo) {
            if( directoryInfo == null ) {
                return false;
            }
            
            if( !_useRecursiveCheck || directoryInfo.GetDirectories().Length == 0 ) {
                return directoryInfo.GetFiles().Length == 0;
            }

            foreach(DirectoryInfo di in directoryInfo.GetDirectories() ) {
                if (!Matches(di))
                    return false;
            }
            // if we get here it is because there are no subdirectories or they are all empty...
            return directoryInfo.GetFiles().Length == 0; 
        }

        /// <summary>
        /// I would like to refactor this from using the System.IO.FileInfo type to 
        /// using a custom FileData type that could easily be extended/wrapped to represent 
        /// FileData for various data sources and file-systems, not just a FAT32 or NTFS file. 
        /// </summary>
        /// <param name="fileInfo"></param>
        /// <returns></returns>
        public override bool Matches(FileInfo fileInfo)
        {
            return false;
        }
    }
}
